<template>
    <div id="rule">
        设备编号 <el-input v-model="deviceCode" placeholder="请输入设备编号" style="width: 150px;"></el-input>
        规则名称 <el-input v-model="name" placeholder="请输入规则名称" style="width: 150px;"></el-input>
        创建时间 <el-date-picker v-model="value1" type="daterange" range-separator="-" start-placeholder="开始日期"
            end-placeholder="结束日期">
        </el-date-picker>
        <el-button type="primary" style="height: 35px;" @click="search(1)"><i class="el-icon-search">搜索</i></el-button>
        <el-button style="height: 35px;" @click="reset"><i class="el-icon-refresh">重置</i></el-button>
        <div style="margin-top: 10px;">
            <el-button type="primary" style="height: 35px;" @click.native="addEquipmentValue"><i
                    class="el-icon-plus">新增</i></el-button>
        </div>
        <el-table :data="sysRuleList">
            <el-table-column prop="id" label="序号" width="60px"> </el-table-column>
            <el-table-column prop="name" label="规则名称" width="80px"> </el-table-column>
            <el-table-column prop="code" label="规则编号" width="80px"> </el-table-column>
            <el-table-column prop="deviceCode" label="设备编号" width="80px"> </el-table-column>
            <el-table-column prop="status" label="使用情况" width="80px">
                <template slot-scope="scope">
                    <span v-if="scope.row.status === 0">未使用</span>
                    <span v-if="scope.row.status === 1">常开时段</span>
                    <span v-if="scope.row.status === 2">常闭时段</span>
                </template>
            </el-table-column>
            <el-table-column label="时间描述" width="800px">
                <template slot-scope="scope">
                    <div v-for="weekNumber in [1, 2, 3, 4, 5, 6, 7]" :key="weekNumber">
                        <p v-if="scope.row['week' + weekNumber]">
                            {{ getChineseWeekday(weekNumber) }}<br>
                            <span v-for="item in scope.row['week' + weekNumber]" :key="item.date || item">
                                时间{{ item.timeInterval }}[{{ item.endTime.join(' ~ ') }}]；
                            </span>
                        </p>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="createDate" label="创建时间" width="160px"> </el-table-column>
            <el-table-column label="操作" width="100px">
                <template slot-scope="scope">
                    <el-tooltip effect="dark" content="修改" placement="top">
                        <el-button type="primary" icon="el-icon-edit" size="mini" circle
                            @click="upd(scope.row)"></el-button>
                    </el-tooltip>
                    <el-tooltip effect="dark" content="删除" placement="top">
                        <el-button type="danger" icon="el-icon-delete" size="mini" circle
                            @click="del(scope.row.id)"></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin-top: 30px;margin-left: 1150px;" v-if="pageCount >= 1">
            <el-button-group>
                <el-button type="primary" icon="el-icon-arrow-left" @click="prevPage">上一页</el-button>
                <el-button><span>{{ pageNum }} / {{ pageCount }}</span></el-button>
                <el-button type="primary" @click="nextPage">下一页<i
                        class="el-icon-arrow-right el-icon--right"></i></el-button>
            </el-button-group>
        </div>
        <el-row v-if="showAdd">
            <el-dialog title="添加人脸规则" :visible.sync="showAdd" width="width">
                <div>
                    <el-form ref="form" :model="form" label-width="80px">
                        <el-form-item label="规则编号">
                            <el-input v-model="form.code" placeholder="请输入规则编号"></el-input>
                        </el-form-item>
                        <el-form-item label="规则名称">
                            <el-input v-model="form.name" placeholder="请输入规则名称"></el-input>
                        </el-form-item>
                        <el-form-item label="使用情况">
                            <el-select v-model="form.usageSituation" placeholder="请选择使用情况">
                                <el-option label="未使用" value="0"></el-option>
                                <el-option label="常开时段" value="1"></el-option>
                                <el-option label="常闭时段" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="设备编号">
                            <el-input v-model="form.deviceCode" placeholder="请输入设备编号"></el-input>
                        </el-form-item>
                        <el-tabs v-model="description">
                            <el-tab-pane v-for="date in dateInWeekList" :key="date.value" :label="date.label"
                                :name="date.value">
                                <el-form-item v-for="i in 4" :key="date.value + '-' + i">
                                    <el-tag type="primary">时段{{ i }}</el-tag>
                                    &nbsp;&nbsp;
                                    <el-time-picker is-range range-separator="-"
                                        v-model="timeRanges.find(item => item.date === date.value && item.timeInterval === i).endTime"
                                        value-format="HH:mm:ss" start-placeholde="开始时间" end-placeholde="结束时间">
                                    </el-time-picker>
                                </el-form-item>
                            </el-tab-pane>
                        </el-tabs>
                    </el-form>
                </div>
                <div slot="footer">
                    <el-button type="primary" @click="add">确 定</el-button>
                    <el-button @click="showAdd = false">取 消</el-button>
                </div>
            </el-dialog>
        </el-row>
        <el-row v-if="showUpd == true">
            <el-dialog title="修改人脸规则" :visible.sync="showUpd" width="width">
                <div>
                    <el-form ref="form" :model="sysRule" label-width="80px">
                        <el-form-item label="规则编号">
                            <el-input v-model="sysRule.code" placeholder="请输入规则编号"></el-input>
                        </el-form-item>
                        <el-form-item label="规则名称">
                            <el-input v-model="sysRule.name" placeholder="请输入规则名称"></el-input>
                        </el-form-item>
                        <el-form-item label="使用情况">
                            <el-select v-model="usageSituation" placeholder="请选择使用情况">
                                <el-option label="未使用" value="0"></el-option>
                                <el-option label="常开时段" value="1"></el-option>
                                <el-option label="常闭时段" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="设备编号">
                            <el-input v-model="sysRule.deviceCode" placeholder="请输入设备编号"></el-input>
                        </el-form-item>
                        <el-tabs v-model="description">
                            <el-tab-pane v-for="date in dateInWeekList" :key="date.value" :label="date.label"
                                :name="date.value">
                                <el-form-item v-for="i in 4" :key="date.value + '-' + i">
                                    <el-tag type="primary">时段{{ i }}</el-tag>
                                    &nbsp;&nbsp;
                                    <el-time-picker is-range range-separator="-"
                                        v-model="timeRanges.find(item => item.date === date.value && item.timeInterval === i).endTime"
                                        value-format="HH:mm:ss" start-placeholde="开始时间" end-placeholde="结束时间">
                                    </el-time-picker>
                                </el-form-item>
                            </el-tab-pane>
                        </el-tabs>
                    </el-form>
                </div>
                <div slot="footer">
                    <el-button type="primary" @click="updSysRule">确 定</el-button>
                    <el-button @click="showUpd = false">取 消</el-button>
                </div>
            </el-dialog>
        </el-row>
    </div>

</template>
<script>
import axios from 'axios';
export default {
    name: 'RuleManager',
    data() {
        return {
            showAdd: false,
            deviceCode: '',
            name: '',
            form: {
                code: '',
                name: '',
                description: '',
                usageSituation: '',
            },
            description: '',
            value1: '',
            dateInWeekList: [
                { value: '1', label: '周日' },
                { value: '2', label: '周一' },
                { value: '3', label: '周二' },
                { value: '4', label: '周三' },
                { value: '5', label: '周四' },
                { value: '6', label: '周五' },
                { value: '7', label: '周六' }
            ],
            timeRanges: [],
            time: '',
            pageNum: 1,
            pageSize: 2,
            pageCount: 0,
            sysRuleList: [],
            startDate: '',
            endDate: '',
            sysRule: {
                code: '',
                name: '',
                description: '',
                usageSituation: '',
            },
            showUpd: false,
        }
    },
    created() {
        this.getSysRuleList(1);
    },
    methods: {
        prevPage() {
            this.pageNum--;
            var pageNum = this.pageNum;
            if (this.pageNum >= 1) {
                this.getSysRuleList(pageNum);
            } else {
                this.getSysRuleList(1);
            }
        },
        nextPage() {
            this.pageNum++;
            var pageNum = this.pageNum;
            if (this.pageNum <= this.pageCount) {
                this.getSysRuleList(pageNum);
            } else {
                this.getSysRuleList(this.pageCount);
            }
        },
        addEquipmentValue() {
            this.showAdd = true;
        },
        add() {
            // let code = this.form.code;
            if (this.form.code === '') {
                this.$message.error('设备编号不能为空！');
                return;
            }
            const integerRegex = /^-?\d+$/;
            if (!integerRegex.test(this.form.code)) {
                this.$message.error('只能输入为整数编号');
                return;
            }
            if(this.form.name === ''){
                this.$message.error('规则名称不能为空！');
                return;
            }
            if(this.form.usageSituation === ''){
                this.$message.error('请选择规则类型！');
                return;
            }
            if(this.form.deviceCode === ''){
                this.$message.error('请输入设备编号！');
                return;
            }
            console.log(this.time);
            this.timeRanges.push(this.time);
            this.timeRanges = this.timeRanges = this.timeRanges.filter(item => {
                return typeof item === 'object' && item !== null;
            });
            console.log('add', this.timeRanges);
            const groupedArrays = [];
            for (let i = 0; i < this.timeRanges.length; i += 4) {
                groupedArrays.push(this.timeRanges.slice(i, i + 4));
            }

            // 此时 groupedArrays 就是包含7个数组的数组，每个子数组包含4个对象
            console.log(groupedArrays);
            function processJSONArray(array) {
                return array.map(item => {
                    if (item.endTime === null) {
                        item.endTime = ["00:00:00", "00:00:00"];
                    }
                    return item;
                });
            }
            const processedArrayData = processJSONArray(this.timeRanges);

            console.log(JSON.stringify(processedArrayData));
            console.log("code:" + this.form.code);
            console.log("name:" + this.form.name);
            console.log("usageSituation:" + this.form.usageSituation);
            console.log("deviceCode:" + this.form.deviceCode);
            let Authorization = localStorage.getItem("Authorization");
            axios({
                url: 'http://localhost:9002/sys/rule/addSysRule',
                method: 'post',
                data: {
                    code: this.form.code,
                    name: this.form.name,
                    status: this.form.usageSituation,
                    deviceCode: this.form.deviceCode,

                    week1: JSON.stringify(groupedArrays[0]),
                    week2: JSON.stringify(groupedArrays[1]),
                    week3: JSON.stringify(groupedArrays[2]),
                    week4: JSON.stringify(groupedArrays[3]),
                    week5: JSON.stringify(groupedArrays[4]),
                    week6: JSON.stringify(groupedArrays[5]),
                    week7: JSON.stringify(groupedArrays[6]),
                },
                headers: {
                    'Authorization': Authorization
                }
            })
                .then(response => {
                    console.log("asxsaxsaxsxxassa");
                    console.log(response);
                    if (response.data.status == 200) {
                        this.$message.success('规则添加成功！');
                        this.showAdd = false;
                        this.getSysRuleList(1);
                    } else if (response.data.status == 500) {
                        this.$message.error('规则添加失败！');
                    }
                })
        },
        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');

            return `${year}-${month}-${day}`;
        },
        getSysRuleList(pageNum) {
            this.pageNum = pageNum;
            if (this.value1 && this.value1.length === 2) {
                const startDate = this.value1[0];
                const endDate = this.value1[1];
                console.log('开始日期：', startDate);
                const formattedStartDate = this.formatDate(startDate);
                const formattedEndDate = this.formatDate(endDate);

                console.log('开始日期：', formattedStartDate);
                console.log('结束日期：', formattedEndDate);
                this.startDate = formattedStartDate,
                    this.endDate = formattedEndDate;
            }
            let Authorization = localStorage.getItem("Authorization");
            axios({
                url: 'http://localhost:9002/sys/rule/getSysRuleList',
                method: 'post',
                params: {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    deviceCode: this.deviceCode,
                    name: this.name,
                    startDate: this.startDate,
                    endDate: this.endDate
                },
                headers: {
                    'Authorization': Authorization
                }
            })
                .then(response => {
                    console.log(response);
                    this.sysRuleList = response.data.data.sysRuleList;
                    this.pageCount = response.data.data.pageCount;
                    this.sysRuleList.forEach((rule) => {
                        if (rule.week1) {
                            try {
                                rule.week1 = JSON.parse(rule.week1);
                            } catch (error) {
                                console.error(`转换失败：${error}`);
                            }
                        }
                        if (rule.week2) {
                            try {
                                rule.week2 = JSON.parse(rule.week2);
                            } catch (error) {
                                console.error(`转换失败：${error}`);
                            }
                        }
                        if (rule.week3) {
                            try {
                                rule.week3 = JSON.parse(rule.week3);
                            } catch (error) {
                                console.error(`转换失败：${error}`);
                            }
                        }
                        if (rule.week4) {
                            try {
                                rule.week4 = JSON.parse(rule.week4);
                            } catch (error) {
                                console.error(`转换失败：${error}`);
                            }
                        }
                        if (rule.week5) {
                            try {
                                rule.week5 = JSON.parse(rule.week5);
                            } catch (error) {
                                console.error(`转换失败：${error}`);
                            }
                        }
                        if (rule.week6) {
                            try {
                                rule.week6 = JSON.parse(rule.week6);
                            } catch (error) {
                                console.error(`转换失败：${error}`);
                            }
                        }
                        if (rule.week7) {
                            try {
                                rule.week7 = JSON.parse(rule.week7);
                            } catch (error) {
                                console.error(`转换失败：${error}`);
                            }
                        }
                    });
                    console.log(this.sysRuleList);
                })
        },
        getChineseWeekday(weekNumber) {
            const weekdays = ['日','一', '二', '三', '四', '五', '六'];
            return `周${weekdays[weekNumber - 1]}`;
        },
        search(pageNum) {
            this.pageNum = pageNum;
            this.getSysRuleList(this.pageNum);
        },
        del(id) {
            let Authorization = localStorage.getItem("Authorization");
            if (confirm("确定删除该条规则吗？")) {
                axios({
                    url: 'http://localhost:9002/sys/rule/delSysRuleById',
                    method: 'post',
                    params: {
                        id: id
                    },
                    headers: {
                        'Authorization': Authorization
                    }
                })
                    .then(response => {
                        console.log(response);
                        this.getSysRuleList(1);
                    })
            }

        },
        reset() {
            this.deviceCode = '';
            this.name = '';
            this.value1 = '';
            this.getSysRuleList(1);
        },
        upd(row) {
            this.sysRule = row;
            this.sysRule.code = row.code;
            this.sysRule.name=row.name;
            this.sysRule.deviceCode=row.deviceCode;
            if (row.status == 0) {
                this.usageSituation = '0';
            } else if (row.status == 1) {
                this.usageSituation = '1';
            } else if (row.status == 2) {
                this.usageSituation = '2';
            }
            console.log(row.week1);
            this.timeRanges = [];
            console.log('this.timeRanges:', this.timeRanges);
            for (let i = 1; i <= 7; i++) {
                const weekArray = row[`week${i}`];
                weekArray.forEach((obj) => {
                    this.timeRanges.push({
                        date: obj.date,
                        timeInterval: obj.timeInterval,
                        endTime: obj.endTime
                    });
                });
            }
            console.log('this.timeRanges:', this.timeRanges);
            this.showUpd = true;
        },
        updSysRule() {
            if (this.sysRule.code === '') {
                this.$message.error('设备编号不能为空！');
                return;
            }
            const integerRegex = /^-?\d+$/;
            if (!integerRegex.test(this.form.code)) {
                this.$message.error('只能输入为整数编号');
                return;
            }
            if(this.sysRule.name === ''){
                this.$message.error('规则名称不能为空！');
                return;
            }
            if(this.sysRule.usageSituation === ''){
                this.$message.error('请选择规则类型！');
                return;
            }
            if(this.sysRule.deviceCode === ''){
                this.$message.error('请输入设备编号！');
                return;
            }
            console.log(this.usageSituation);
            this.timeRanges.push(this.time);
            this.timeRanges = this.timeRanges = this.timeRanges.filter(item => {
                return typeof item === 'object' && item !== null;
            });
            console.log('add', this.timeRanges);
            const groupedArrays = [];
            for (let i = 0; i < this.timeRanges.length; i += 4) {
                groupedArrays.push(this.timeRanges.slice(i, i + 4));
            }

            // 此时 groupedArrays 就是包含7个数组的数组，每个子数组包含4个对象
            console.log(groupedArrays);
            function processJSONArray(array) {
                return array.map(item => {
                    if (item.endTime === null) {
                        item.endTime = ["00:00:00", "00:00:00"];
                    }
                    return item;
                });
            }
            const processedArrayData = processJSONArray(this.timeRanges);
            console.log(processedArrayData);

            let Authorization = localStorage.getItem("Authorization");
            axios({
                url: 'http://localhost:9002/sys/rule/updSysRuleById',
                method: 'post',
                data: {
                    code: this.sysRule.code,
                    name: this.sysRule.name,
                    status: this.usageSituation,
                    deviceCode: this.sysRule.deviceCode,

                    week1: JSON.stringify(groupedArrays[0]),
                    week2: JSON.stringify(groupedArrays[1]),
                    week3: JSON.stringify(groupedArrays[2]),
                    week4: JSON.stringify(groupedArrays[3]),
                    week5: JSON.stringify(groupedArrays[4]),
                    week6: JSON.stringify(groupedArrays[5]),
                    week7: JSON.stringify(groupedArrays[6]),
                    id:this.sysRule.id
                },
                headers: {
                    'Authorization': Authorization
                }
            })
            .then(response => {
                console.log(response);
                if(response.data.status == 200){
                    this.$message.success('修改成功');
                    this.getSysRuleList(1);
                    this.showUpd = false;
                    
                }else{
                    this.$message.error('修改失败');
                }
            })
        }
    },
    mounted() {
        this.dateInWeekList.forEach(date => {
            for (let i = 1; i <= 4; i++) {
                const timeRangeItem = {
                    date: date.value,
                    timeInterval: i,
                    //   startTime: null,
                    endTime: null
                };
                this.timeRanges.push(timeRangeItem);
            }
        });
        // 更新 v-model 绑定的值以显示默认值
        this.dateInWeekList.forEach(date => {
            for (let i = 1; i <= 4; i++) {
                const timeRange = this.timeRanges.find(item => item.date === date.value && item.timeInterval === i);
                if (timeRange) {
                    const timePicker = this.$refs[`timePicker_${date.value}_${i}`];
                    if (timePicker) {
                        // timePicker.startTime = timeRange.startTime;
                        timePicker.endTime = timeRange.endTime;
                    }

                }
            }
        });
    }
}
</script>